﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Upreader.Usenet.Nntp.Encodings
{
    public class YencStreamDecoder : IStreamDecoder
    {
        public bool TryCreateDecodeStreamFactory(Stream stream, out Func<Stream, Stream> decodeStreamFactory)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            // create a streamReader with a minimal buffer since we will be able to find out of this Stream is yEncoded pretty quickly
            NntpStreamReader reader = new NntpStreamReader(stream, NntpClient.DefaultTextEncoding, 1);

            // initial value
            decodeStreamFactory = null;

            while (!reader.EndOfStream)
            {
                string line = reader.ReadLine();

                // there might be some initial lines on the top
                if (!string.IsNullOrEmpty(line))
                {
                    if (line.StartsWith("=y"))
                    {
                        // we can assume that this is a yEncoded stream.
                        decodeStreamFactory = input =>
                        {
                            return new YencEncodedStream(input);
                        };
                    }
                    else
                    {
                        // if the first line is no yenc line, this stream is no yEncoded stream
                        // or it's garbled in which case we cant decode it anyways  
                        decodeStreamFactory = null;
                    }

                    // break from the outer while loop
                    break;
                }
            }

            return decodeStreamFactory != null;
        }
    }
}
